var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js');


/* 收货地址查询 */
router.post('/api/selectAddress', function(req, res, next) {
	let phone = req.body.phone
	// 根据电话查找用户
	connection.query(
		`select * from user where phone = "${phone}"`,
		function(er, ress, field) {
			if (er) throw er
			let userId = ress[0].id
			connection.query(
				`select * from address where userId = ${userId}`,
				function(er, result, field) {
					if (er) throw er
					res.send({
						success: true,
						data: result
					})
				})
		})
})

/* 新增收货地址 */
router.post('/api/addAddress', function(req, res, next) {
	let phone = req.body.phone
	let province = req.body.province
	let city = req.body.city
	let district = req.body.district
	let details = req.body.details
	let name = req.body.name
	let isDefalt = req.body.isDefalt
	let tel = req.body.tel
	// 根据电话查找用户
	connection.query(`select * from user where phone = "${phone}"`,
		function(er, ress, field) {
			if (er) throw er
			let userId = ress[0].id
			// 新增地址
			connection.query(
				`insert into address (name,tel,province,city,district,details,isDefalt,userId)
				 values ('${name}','${tel}','${province}','${city}','${district}','${details}','${isDefalt}',${userId})`,
				function(er, result, field) {
					if (er) throw er
					res.send({
						data: {
							success: true,
							msg: '新增地址成功'
						}
					})
				})
		})
})

/* 修改收货地址 */
router.post('/api/updateAddress', function(req, res, next) {
	let phone = req.body.phone
	let province = req.body.province
	let city = req.body.city
	let district = req.body.district
	let details = req.body.details
	let name = req.body.name
	let isDefalt = req.body.isDefalt
	let tel = req.body.tel
	let id = req.body.id
	// 根据电话查找当前用户
	connection.query(`select * from user where phone = "${phone}"`,
		function(er, ress) {
			if (er) throw er
			let userId = ress[0].id
			// 查询出默认地址数据
			connection.query(`select * from address where userId =${userId} and isDefalt=${isDefalt}`,
				function(error, results) {
					if (error) throw error
					let childId = results[0].id;
					// 更新当前默认为不默认
					connection.query(
						`update address set isDefalt = replace(isDefalt,'1','0') where id =${childId}`,
						function(err, result) {
							if (err) throw err
							// 修改地址
							connection.query(
								`update address set name='${name}',tel='${tel}',province='${province}',city='${city}',district='${district}',details='${details}',isDefalt='${isDefalt}',userId=${userId} where id = ${id}`,
								function(er, result) {
									if (er) throw er
									res.send({
										data: {
											success: true,
											msg: '修改地址成功'
										}
									})
								})
						})
				})
		})
})

module.exports = router;
